package com.github.kaelthasbmg.factory.generate;

import com.github.kaelthasbmg.bean.DataBaseDefine;
import com.github.kaelthasbmg.bean.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;

/**
 * DDL构造类
 *
 * @author Carsymor
 */
public abstract class Generator {
    /**
     * 数据库连接
     */
    protected Connection connection;

    /**
     * 数据库结构中的元素定义
     */
    protected DataBaseDefine dataBaseDefine;

    protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    public Generator(Connection connection, DataBaseDefine dataBaseDefine) {
        this.connection = connection;
        this.dataBaseDefine = dataBaseDefine;
    }

    /**
     * 构造数据库结构
     */
    public void generateStructure() {
        this.createTable(dataBaseDefine.getTables());
    }

    /**
     * 创建表结构
     * @param tableDefines 表结构定义
     */
    protected void createTable(List<Table> tableDefines) {
        if (tableDefines != null && !tableDefines.isEmpty()) {
            String tableDDL = null;
            try(
                Statement statement = this.connection.createStatement();
            ) {
                for (Table table : tableDefines) {
                    tableDDL = this.getTableDDL(table);
                    statement.execute(tableDDL);
                    logger.info("表{}创建成功", table.getTableName());
                }
            } catch (Throwable e) {
                logger.error(String.format("创建表失败，DDL：%s", tableDDL), e);
            }

        }
    }

    /**
     * 获取创建表的DDL语句
     * @param tableDefine 表结构定义
     * @return 创建表的DDL语句
     */
    protected abstract String getTableDDL(Table tableDefine);
}
